#include <Python.h>
#include <iostream>
#include <direct.h>
#include <mirai.h>
#include <string>
#include <stdio.h>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;

string _down(int d)
{
	// 初始化Python环境
	Py_Initialize();
	// 判断初始化是否成功  
	if (!Py_IsInitialized())
	{
		cout << "Initialize failed ..." << endl;
		// 关闭 Python 脚本解释器，释放内存。
		Py_Finalize();
	}
	cout << "初始化成功" << endl;
	PyObject* pModule = NULL;
	PyObject* pFunc = NULL;
	PyObject* pArg = NULL;

	//// 添加模块路径
	PyRun_SimpleString("import sys");
	PyRun_SimpleString("sys.path.append('E:/学习相关/C++/testCode/mirai-cpp-template/src')");

	cout << "添加模块路径" << endl;
	// 导入模块
	pModule = PyImport_ImportModule("dl");
	if (!pModule) // 检查模块是否导入成功
	{
		cout << "Python file import failed ..." << endl;
		Py_Finalize();
	}
	else
	{
		cout << "导入模块" << endl;
		// 导入函数
		pFunc = PyObject_GetAttrString(pModule, "_dl"); //python 脚本里的函数名
		if (!pFunc) // 检查函数是否导入成功
		{
			cout << "Function import failed ..." << endl;
			Py_Finalize();
		}
		cout << "导入函数" << endl;
		PyObject* pParams = Py_BuildValue("(i)", d);
		cout << "通过" << endl;
		char* result;

		cout << "调用函数" << endl;
		pArg = PyEval_CallObject(pFunc, pParams); // 调用函数
		cout << "调用函数完成" << endl;
		   //获取结果，python类型转换为C++类型。
		PyArg_Parse(pArg, "s", &result);

		//ofstream ofs;
		//ofs.open("E:/学习相关/C++/testCode/mirai-cpp-template/result.txt",ios::trunc);
		//if (ofs.is_open())
		//{
		//	ofs << result;
		//}
		//ofs.close();
		
		//if (pArg)
		//{
		//	Py_DECREF(pArg);
		//	cout << "pArg释放成功" << endl;
		//}
		//if (pParams)
		//{
		//	Py_DECREF(pParams);
		//	cout << "pParams释放成功" << endl;
		//}
		//if (pFunc)
		//{
		//	Py_DECREF(pFunc);
		//	cout << "pFunc释放成功" << endl;
		//}
		//if (pModule)
		//{
		//	Py_DECREF(pModule);
		//	cout << "pModule释放成功" << endl;
		//}

		Py_Finalize();
		cout << "Py_Finalize成功" << endl;
		cout << result << endl;
		string directory = "E:\\学习相关\\C++\\testCode\\mirai-cpp-template\\temp_img\\";
		Mat src = imread(directory + result + ".Webp");
		src.depth();
		string const& temp_address = directory + result + ".Webp";
		char const * old_address = temp_address.c_str();
		cout << directory + result + ".Webp" << endl;
		cout<<imwrite(directory + result + ".png",src)<<endl;
		remove(old_address);
		cout << "删除Webp版本成功" << endl;
		return result;

	}
	Py_Finalize();
}

//void main()
//{
//	_down(3);
//}